<?php
class SQLOperation {
	private $server;
	private $database;
	private $con;
	
	public function __construct($server, $database) {
		$this->server = $server;
		$this->database = $database;
	}
	
	public function connect() {
		$user = "root";
		$password = "";
		$this->con = mysql_connect($this->server, $user, $password);
		if (!$this->con) {
			return 0;
		}
		
		return $this->setOperateDatabase($this->database);
	}

	private function setOperateDatabase($database) {
		$ret = mysql_select_db($database);
		
		return !$ret ? 0 : 1;
	}
	
	private function genFormattedString($args, $isValue) {		
		if (is_array($args)) {
			$args_str = " (";
			if ($isValue) {
				foreach ($args as $arg) {
					$args_str .= "'".$arg."',";
				}
			} else {
				foreach ($args as $arg) {
					$args_str .= $arg.",";
				}
			}
			
			$args_str = rtrim($args_str, ',');
			$args_str .= ") ";
			return $args_str;
		}
		
		return $args;
	}
	
	private function setCharacterSet() {
		mysql_query("SET NAMES UTF8");
		mysql_query("set character_set_client=utf8");
		mysql_query("set character_set_results=utf8");
	}
	
	public function insert($table, $fields, $values) {
		$fileds_str = $this->genFormattedString($fields, false);
		$values_str = $this->genFormattedString($values, true);
		
		$sql = "INSERT INTO ".$table.$fileds_str."VALUES".$values_str;
		$this->setCharacterSet();
		$result = mysql_query($sql, $this->con);
		
		return !$result ? 0 : 1;
	}
	
	public function update($table, $update, $where) {		
		$sql = "UPDATE ".$table." SET ".$update." WHERE ".$where;
		$this->setCharacterSet();
		$result = mysql_query($sql, $this->con);
		
		return !$result ? 0 : 1;
	}
	
	public function query($table, $querys, $where) {
		$query_str = "";
		if (is_array($querys)) {
			foreach ($querys as $query) {
				$query_str .= $query.",";
			}
			$query_str = rtrim($query_str, ',');
		} else {
			$query_str = $querys;
		}
		
		if (strlen($where) == 0) {
			$sql = "SELECT ".$query_str." FROM ".$table;
		} else {
			$sql = "SELECT ".$query_str." FROM ".$table." WHERE ".$where;
		}
		$this->setCharacterSet();
		$result = mysql_query($sql, $this->con);
		
		return $result;
	}
	
	public function close() {
		if ($this->con) {
			mysql_close($this->con);
		}
	}
}
?>